package com.bitters.fileupload.common.file;

import com.bitters.fileupload.entity.FileProgressEntity;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

/**
 * @author thomashe
 * @date 2022/5/30
 **/
@Component
public class FileUploadProgressListener implements ProgressListener {

    private HttpSession session;

    public void setSession(HttpSession session) {
        this.session = session;
        //保存上传状态
        FileProgressEntity progressEntity = new FileProgressEntity();
        session.setAttribute("fileProgressEntity", progressEntity);
    }

    @Override
    public void update(long bytesRead, long contentLength, int files) {
        FileProgressEntity progressEntity = (FileProgressEntity) session.getAttribute("fileProgressEntity");
        progressEntity.setBytesRead(bytesRead);
        progressEntity.setContentLength(contentLength);
        progressEntity.setFiles(files);
        logger.info("FileUploadProgressListener status   :  " + progressEntity.toString());
    }

    final Logger logger = LoggerFactory.getLogger(FileUploadProgressListener.class);
}
